#include "TestTexture2D.h"

#include "Renderer.h"
#include "imgui/imgui.h"

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"


#include "Shader.h"
#include "VertexArray.h"

test::TestTexture2D::TestTexture2D()
    : m_TranslationA(0.5, 0.5, 0), m_TranslationB(0.8, 0.8, 0)
{
   float positions[] = {
        -0.5f, -0.5f, 0.0f, 0.0f,
        0.5f, -0.5f, 1.0f, 0.0f,
        0.5f, 0.5f, 1.0f, 1.0f,
        -0.5f, 0.5f, 0.0f, 1.0f
    };

    uint32_t indices[] = {
        0, 1, 2,
        2, 3, 0
    };

	GLCall(glEnable(GL_BLEND));
	GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));

	m_VertexBuffer = std::make_unique<VertexBuffer>(positions, 4 * 4 * sizeof(float));
	m_VAO = std::make_unique<VertexArray>();

	VertexBufferLayout layout;
	layout.Push<float>(2);
	layout.Push<float>(2);
	m_VAO->AddBufffer(*m_VertexBuffer, layout);

	m_Proj = glm::ortho(-2.0f, 2.0f, -1.5f, 1.5f, -1.0f, 1.0f);
	m_View = glm::translate(glm::mat4(1.0f), glm::vec3(-0, 0, 0));


	m_IndexBuffer =  std::make_unique<IndexBuffer>(indices, 6);

	m_Shader = std::make_unique<Shader>("res/shaders/Basic.shader");
	m_Shader->Bind();

	m_Texture = std::make_unique<Texture>("res/textures/glider.png");
	m_Texture->Bind();
	m_Shader->SetUniform1i("u_Texture", 0);
	// Unbind
	m_IndexBuffer->Unbind();
	m_VertexBuffer->Unbind();
	m_VAO->Unbind();
	m_Shader->Unbind();
}

test::TestTexture2D::~TestTexture2D()
{
}

void test::TestTexture2D::OnUpdate(float deltaTime)
{

}

void test::TestTexture2D::OnRender()
{

	Renderer renderer;
	{
		glm::mat4 model = glm::translate(glm::mat4(1.0f), m_TranslationA);
		glm::mat4 mvp = model * m_View * m_Proj;
		m_Shader->Bind();
		m_Shader->SetUniform4f("u_Color", 0.2f, 0.5f, 0.1f, 1.0f);
		m_Shader->SetUniformMat4fv("u_MVP", mvp);
		renderer.Draw(*m_VAO, *m_IndexBuffer, *m_Shader);
	}

	{
		glm::mat4 model = glm::translate(glm::mat4(1.0f), m_TranslationB);
		glm::mat4 mvp = model * m_View * m_Proj;
		m_Shader->Bind();
		m_Shader->SetUniform4f("u_Color", 0.2f, 0.5f, 0.1f, 1.0f);
		m_Shader->SetUniformMat4fv("u_MVP", mvp);
		renderer.Draw(*m_VAO, *m_IndexBuffer, *m_Shader);
	}

}

void test::TestTexture2D::OnImGuiRender()
{
	ImGui::SliderFloat3("translatonA", &m_TranslationA.x, -1.0f, 1.0f);
	ImGui::SliderFloat3("translatonB", &m_TranslationB.x, -1.0f, 1.0f);
	ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}

